package com.my.easyrules.db.helper;

import org.jeasy.rules.api.Rule;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.mvel.MVELRule;
import org.jeasy.rules.support.AbstractRuleFactory;
import org.jeasy.rules.support.RuleDefinition;
import org.mvel2.ParserContext;

import java.util.List;

/**
 * @Description: 业务规则工具类
 */
public class BizRuleHelper extends AbstractRuleFactory {

    private final ParserContext parserContext;

    public BizRuleHelper(ParserContext parserContext) {
        this.parserContext = parserContext;
    }

    /**
     * 创建规则
     * @param ruleDefinitions 规则定义
     * @return 结果
     */
    public Rules createRules(List<RuleDefinition> ruleDefinitions) {
        Rules rules = new Rules();
        ruleDefinitions.forEach(ruleDefinition -> rules.register(createRule(ruleDefinition)));
        return rules;
    }

    @Override
    public Rule createSimpleRule(RuleDefinition ruleDefinition) {
        MVELRule mvelRule = new MVELRule(parserContext)
                .name(ruleDefinition.getName())
                .description(ruleDefinition.getDescription())
                .priority(ruleDefinition.getPriority())
                .when(ruleDefinition.getCondition());
        for (String action : ruleDefinition.getActions()) {
            mvelRule.then(action);
        }
        return mvelRule;
    }
}